package com.ljj.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljj.eduservice.entity.EduChapter;
import com.ljj.eduservice.entity.EduCourse;
import com.ljj.eduservice.entity.EduCourseDescription;
import com.ljj.eduservice.entity.EduVideo;
import com.ljj.eduservice.entity.frontvo.CourseFrontVo;
import com.ljj.eduservice.entity.frontvo.CourseWebVo;
import com.ljj.eduservice.entity.vo.CourseInfoVo;
import com.ljj.eduservice.entity.vo.CoursePublishVo;
import com.ljj.eduservice.mapper.EduCourseMapper;
import com.ljj.eduservice.service.EduChapterService;
import com.ljj.eduservice.service.EduCourseDescriptionService;
import com.ljj.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljj.eduservice.service.EduVideoService;
import com.ljj.servicebase.handler.MicroCloudException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-09-11
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService descriptionService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private EduVideoService videoService;



    /**
     * 保存课程信息
     * @param courseInfoVo
     * @return
     */
    @Override
    public String saveCourse(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);

        if(insert==0){
            throw new MicroCloudException(20001,"添加失败");
        }

        String courseId = eduCourse.getId();

        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseId);
        description.setDescription(courseInfoVo.getDescription());
        descriptionService.save(description);

        return courseId;
    }

    /**
     * 根据课程Id获取课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        EduCourse course = baseMapper.selectById(courseId);;
        EduCourseDescription description = descriptionService.getById(courseId);
        CourseInfoVo courseInfo = new CourseInfoVo();
        BeanUtils.copyProperties(course,courseInfo);
        courseInfo.setDescription(description.getDescription());
        return courseInfo;
    }

    /**
     * 修改课程信息
     * @param courseInfoVo
     */
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1 修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        if(baseMapper.updateById(eduCourse) == 0) {
            throw new MicroCloudException(20001,"修改失败");
        }

        //2 修改描述表
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());

        if(!descriptionService.updateById(description)) {
            throw new MicroCloudException(20001,"修改失败");
        }

    }

    /**
     * 根据课程Id查询课程信息（发布确认）
     * @param id
     * @return
     */
    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        return baseMapper.getPublishCourseInfo(id);
    }

    /**
     * 根据Id删除课程的所有信息（小节、章节、简介、课程）
     * @param id
     * @return
     */
    @Override
    public boolean deleteCourseByID(String id) {
        //删除小节
        videoService.removeVideoByCourseId(id);

        //删除章节
        chapterService.removeChapterByCourseId(id);

        //删除课程简介
        descriptionService.removeById(id);

        //删除课程本身
        int result = baseMapper.deleteById(id);
        return result>0;
    }

    /**
     * 前台 查询前8课程，用作推荐
     * @return
     */
    @Override
    @Cacheable(value = "front",key = "'courses'")//前台的首页数据缓存，后台新增或修改时删除缓存
    public List<EduCourse> frontCourses() {
        //查询前8课程
        QueryWrapper<EduCourse> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.orderByDesc("id");
        courseQueryWrapper.last("limit 8");
        List<EduCourse> frontCourses =  baseMapper.selectList(courseQueryWrapper);
        return frontCourses;
    }

    /**
     * 前台课程列表，分页条件查询
     * @param pageCourse
     * @param courseFrontVo
     * @return
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageCourse, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) { //一级分类
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())) { //二级分类
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) { //最新
            wrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {//价格
            wrapper.orderByDesc("price");
        }
        baseMapper.selectPage(pageCourse,wrapper);

        List<EduCourse> records = pageCourse.getRecords();
        long current = pageCourse.getCurrent();
        long pages = pageCourse.getPages();
        long size = pageCourse.getSize();
        long total = pageCourse.getTotal();
        boolean hasNext = pageCourse.hasNext();//下一页
        boolean hasPrevious = pageCourse.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        return map;
    }

    /**
     * 根据课程ID查询课程信息，用于前台课程详情显示
     * @param courseId
     * @return
     */
    @Override
    public CourseWebVo getFrontCourseInfo(String courseId) {
        CourseWebVo courseWebVo = baseMapper.getWebCourseInfo(courseId);
        return courseWebVo;
    }


}
